<?php

namespace Frieza\Modules\FansOnboarding\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\OnBoardingFansIncrease;
use Doraemon\model\Fans;
use Doraemon\model\Member;
use Doraemon\model\OnBoardingFansBase;
use Doraemon\pockets\constInterface\UserGrowth\OnBoardingTag;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class FansOnboardingController extends Controller
{
    public function list(Content $content, Request $request)
    {
        $where = [
            'status' => 1,
        ];

        //同步数据库数据到redis中
        $aUid = OnBoardingFansBase::select('uid', [
            'AND' => $where,
        ]);
        Log::debug("ob uids", compact('aUid'));
        OnBoardingFansIncrease::addOnBoardingFans(OnBoardingTag::COLLECTION_BASE, $aUid);


        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $limit = [($page - 1) * $pageSize, $pageSize];

        $rows = OnBoardingFansBase::select('*', [
            'AND' => $where,
            'LIMIT' => $limit,
            "ORDER" => array(
                "id" => "DESC"
            ),
        ]);

        //补充其他字段信息
        foreach ($rows as $key => $row) {
            $nick = Member::get('nick', ['uid' => $row['uid']]);
            $rows[$key]['nickname'] = $nick;
            $rows[$key]['admin_name'] = Admin::user()->find($row['admin_uid'])->name;

            $rows[$key]['fans_add'] = Fans::getCountByWhere([
                'uid' => $row['uid'],
                'act_from' => 'onboarding',
                'addtime[>]' => $row['addtime'],
            ]);
        }

        $list = [
            'list' => $rows,
            'total' => OnBoardingFansBase::count($where),
        ];

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'keyName' => 'circle_id',
            'perPage' => 10,
        ]);

        $grid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableFilter();
            $grid->paginate(10);
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->equal('circle_name', '圈子名称');
            });

            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->column('uid', 'uid');
            $grid->column('nickname', '用户昵称');
            $grid->column('fans_add', '自配置日起已涨粉数量');
            $grid->column('end_at', '配置日期')->display(function () {
                return date('Y-m-d H:i:s', $this->addtime);
            });
            $grid->column('admin_name', '操作人');

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->row->setKeyName('id');
                $actions->disableDelete();
                $actions->disableEdit();

                $actions->append('<a data-id="' . $actions->row->id . '"  data-opt = "删除" href="javascript:;" class="fa fa-eye received-package">删除</a>');
            });

            Admin::script($this->optionSubmit());
        });

        return $content
            ->header('OB-推荐住友涨粉工具')
            ->body($grid);
    }


    public function del(Request $request)
    {
        $rowId = $request->input('id', 1);
        $rowId = intval($rowId);
        if (empty($rowId)) {
            return [
                'code' => 0,
                'msg' => '操作不合法',
            ];
        }

        $timestamp = time();
        try {
            $targetUid = OnBoardingFansBase::getOnBoardingProductTag(['id' => $rowId], 'uid');
            if ($targetUid) {
                //删除缓存中的数据
                OnBoardingFansIncrease::rmOnBoardingFans(OnBoardingTag::COLLECTION_BASE, $targetUid);
            }
            OnBoardingFansBase::deleteRowById($rowId);

            return [
                'code' => 1,
                'msg' => '删除成功',
            ];
        } catch (\Exception $e) {
            return [
                'code' => 0,
                'msg' => '删除失败',
            ];
        }
    }

    public function create(Content $content)
    {
        $form = new Form();
        $form->text('uid', '目标用户uid')->required()->placeholder('输入uid，多个uid以英文逗号分隔');
        $form->action('/admin/FansOnboarding/save');

        return $content
            ->header('新建涨粉任务')
            ->breadcrumb(['text' => '涨粉任务', 'url' => '/FansOnboarding/list'], ['text' => '新建涨粉任务'])
            ->body($form);
    }


    public function save(Request $request)
    {
        try {
            $params = $request->all();

            $aUid = explode(',', $params['uid']);
            if (empty($aUid)) {
                $error = new MessageBag([
                    'title' => "用户uid不合法1",
                ]);
                return back()->with(compact('error'))->withInput();
            }

            if (count($aUid) > 100) {
                $error = new MessageBag([
                    'title' => "一次最多指定100个用户",
                ]);
                return back()->with(compact('error'))->withInput();
            }

            $aUsers = Member::select('uid', [
                'uid' => $aUid,
            ]);
            if (empty($aUsers) || count($aUsers) != count($aUid)) {
                Log::error("用户uid不合法2", compact('aUsers', 'aUid'));
                $error = new MessageBag([
                    'title' => "用户uid不合法2",
                ]);
                return back()->with(compact('error'))->withInput();
            }

            $timestamp = time();
            foreach ($aUid as $tmpUid) {
                $stmt = OnBoardingFansBase::insert([
                    'uid' => $tmpUid,
                    'admin_uid' => Admin::user()->id,
                    'status' => 1,
                    'addtime' => $timestamp,
                ]);
                if ($stmt->rowCount()) {
                    OnBoardingFansIncrease::addOnBoardingFans(OnBoardingTag::COLLECTION_BASE, $tmpUid);
                }
            }

            return redirect(url("/admin/FansOnboarding/list"));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }


    //所选操作提交
    public function optionSubmit()
    {
        return <<<SCRIPT
           
            $('.received-package').unbind('click').click(function() {
            var id = $(this).data('id');
            var opt = $(this).data('opt');
            swal({
                title: "是否确认"+opt+"?",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.post('/admin/FansOnboarding/del', {'id':id}, function (data) {
                             $.pjax.reload('#pjax-container');
                             if(data.code == 1) {
                                swal(data.msg, '', 'success');
                             } else {
                                swal(data.msg, '', 'error');
                             }                                                                                                                                    
                        });
                }
            });
        });
SCRIPT;
    }
}
